layui.use(['laydate', 'layer', 'form', 'configs', 'template','util'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        template = layui.template,
        config = layui.configs,
        util = layui.util;
    var tableRender = null;
    var areaId = null;
    var today = {
        tableName: 'mo_data_rec',
        tableNameShow: formatDate(new Date()).split(' ')[0],
    };
    initAll();

    function initAll(){
        getTableOption();
        getArea();
        initDate();
    }

    function initDate(startValue){
        var st = new Date(new Date().getTime() - 3600*1000 );
        startValue = startValue || st;
        laydate.render({
            elem: '#startDate',
            value: secondZero(startValue),
            // format: 'yyyy-MM-dd HH:mm:ss',
            type: 'time',
            ready: function(date){
                var hourLi = $('.laydate-time-show .laydate-time-list > li:nth-child(2)');
                hourLi.nextAll().remove();
                $('.laydate-time-show .laydate-time-list > li').css("width", "50%");
            }
        });
        laydate.render({
            elem: '#endDate',
            value: secondZero(new Date()),
            // format: 'yyyy-MM-dd HH:mm:ss',
            type: 'time',
            ready: function(date){
                var hourLi = $('.laydate-time-show .laydate-time-list > li:nth-child(2)');
                hourLi.nextAll().remove();
                $('.laydate-time-show .laydate-time-list > li').css("width", "50%");
            }
        });
    };

    //获取 table-name
    function getTableOption() {
        $.ajax({
            url: config.motorBaseUrl + "/mo_data_rec/select/tabeName/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".tableMenu").html(template("table-name-tpl", result));
                    var opt = `<option value="${today.tableName}" selected>${today.tableNameShow}</option>`;
                    $(".tableMenu").prepend(opt);
                    form.render('select');
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".areaMenu").html(template("motor-areas-tpl", result));
                    form.render('select');
                    //监听区域选择
                    form.on('select(areaMenu)', function(data) {
                        $(".troughMenu").html("");
                        $(".motorMenu").html('<option value="0">全部</option>');
                        areaId = data.value;
                        getTrough(areaId);
                    });
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //按区域查槽位
    function getTrough(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_trough/selectAreaTrough/v1.0",
            type: "post",
            datatype: "json",
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".troughMenu").html(template("motor-trough-tpl", result));
                    form.render('select');
                    //监听槽位选择
                    form.on('select(troughMenu)', function(data) {
                        $(".motorMenu").html("");
                        var troughId = data.value;
                        getMotors(troughId);
                    });
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    // 按槽位查马达
    function getMotors(troughId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                troughId: troughId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".motorMenu").html(template("motors-tpl", result));
                    form.render('select');
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //查询
    $(".exportBtn").click(function () {
        form.on('submit(download)', function(data){
            // 从 tableName 截取日期   "mo_data_rec_20200313000001"
            var date = '';
            if(data.field.tableName === today.tableName){
                date = today.tableNameShow
            }else{
                var dateStr = data.field.tableName.slice(12,20);  // 20200313
                date = dateStr.slice(0,4) + '-' + dateStr.slice(4,6) + '-' + dateStr.slice(6);
            }
            var fieldData = {
                tableName: data.field.tableName,
                areaId:data.field.areaId,
                troughId: data.field.troughId,
                moId: data.field.moId,
                plcState: data.field.plcState,
                startTime: date + ' ' + data.field.startTime,
                endTime: date + ' ' + data.field.endTime,
            };
            // console.log(fieldData);
            motorDownload(fieldData);
            return false;
        });
    });

    // 下载
    function motorDownload(data) {
        let kv = ''
        for (const k in data) {
          kv += k + '=' + data[k] + '&'
        }
        const url = config.motorBaseUrl + '/download/?' + kv
        window.open(url, '__blank')
    }

    // 时间秒数为00
    function secondZero(date) {
        var date = date || new Date();
        var h = date.getHours();
        h = h < 10 ? '0' + h : h;
        var m = date.getMinutes();
        m = m < 10 ? '0' + m : m;
        return h+':'+m+':00';
    }
});